﻿using System;
using System.Collections;
using System.Security.Permissions;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml;

namespace SiteFox.WebParts.Blog
{
    [AspNetHostingPermission(SecurityAction.Demand,
      Level = AspNetHostingPermissionLevel.Minimal)]
    [AspNetHostingPermission(SecurityAction.InheritanceDemand,
      Level = AspNetHostingPermissionLevel.Minimal)]
    
    public class ArchivesWP : WebPart
    {
        #region PublicProperies
        private string _ViewByArchiveUrl = "Default.aspx";
        [Personalizable(true)]
        [WebBrowsable(true)]
        [WebDescription("")]
        [WebDisplayName("View by archive url")]
        public string ViewByArchiveUrl
        {
            get { return _ViewByArchiveUrl; }
            set { _ViewByArchiveUrl = value; }
        }

        private string _XsltUrl = "~/System/Design/xslt/WebParts/Blog/Archives.xslt";
        [Personalizable(true)]
        [WebBrowsable(true)]
        [WebDescription("")]
        [WebDisplayName("XSL-T url")]
        public string XsltUrl
        {
            get { return _XsltUrl; }
            set { _XsltUrl = value; }
        }

        private int _Archives = 24;
        [Personalizable(true)]
        [WebBrowsable(true)]
        [WebDescription("")]
        [WebDisplayName("Archives")]
        public int Archives
        {
            get { return _Archives; }
            set { _Archives = value; }
        }
        #endregion

        protected override void CreateChildControls()
        {
            Controls.Clear();
            Xml _Xml = new Xml();
            _Xml.TransformSource = _XsltUrl;
            XmlDocument _XmlDocument = new XmlDocument();
            XmlDeclaration _XmlDeclaration = _XmlDocument.CreateXmlDeclaration("1.0", "utf-8", null);
            XmlElement _XmlArchives = _XmlDocument.CreateElement("Archives");
            _XmlDocument.InsertBefore(_XmlDeclaration, _XmlDocument.DocumentElement);
            _XmlDocument.AppendChild(_XmlArchives);
            for (int i = 0; i < _Archives; i++)
            {
                DateTime _Archive = DateTime.Now.AddMonths(-(i+1));
                XmlElement _XmlArchive = _XmlDocument.CreateElement("Archive");
                _XmlArchive.SetAttribute("Year", _Archive.Year.ToString());
                _XmlArchive.SetAttribute("Month", _Archive.Month.ToString());
                _XmlArchive.SetAttribute("MonthName", _Archive.ToString("MMMM"));
                _XmlArchive.SetAttribute("Url", _ViewByArchiveUrl + "?Date=" + _Archive.Year.ToString() + "-" + _Archive.Month.ToString());
                _XmlArchives.AppendChild(_XmlArchive);
            }
            _Xml.DocumentContent = _XmlDocument.InnerXml;
            Controls.Add(_Xml);
        }
    }
}
